package com.dandelion.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dandelion.business.entity.SysMenu;
import com.dandelion.business.entity.vo.LoginUserDetail;
import com.dandelion.business.entity.vo.login.resp.Menu;
import com.dandelion.business.entity.vo.menu.req.MenuReqVO;
import com.dandelion.business.entity.vo.user.CurrentUser;
import com.dandelion.business.mapper.SysMenuMapper;
import com.dandelion.business.service.ISysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dandelion.framework.common.R;
import com.dandelion.framework.common.RedisKey;
import com.dandelion.framework.enums.CodeEnum;
import com.dandelion.framework.enums.DelEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author 宋发准
 * @since 2021-12-26
 */
@Service
@Slf4j
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 菜单列表
     *
     * @param userId 用户id
     * @return {@link List}<{@link Menu}>
     */
    @Override
    public R<List<Menu>> menuList(Long userId) {
        String key = RedisKey.LoginModule.LOGIN_USER_INFO_PREFIX + userId;
        String str = redisTemplate.opsForValue().get(key);
        LoginUserDetail loginUserDetail = JSONUtil.toBean(str, LoginUserDetail.class);
        return R.ok().data(loginUserDetail);
    }


    /**
     * 添加
     *
     * @param currentUser  当前用户
     * @param req 要求事情
     * @return {@link R}
     */
    @Override
    public R<Boolean> add(CurrentUser currentUser, MenuReqVO req) {
        try {
            //检查权限标识是否存在
            SysMenu menu = new SysMenu();
            BeanUtil.copyProperties(req, menu);
            menu.setCreateBy(currentUser.getUserId());
            menu.setCreateTime(LocalDateTime.now());
            menu.setUpdateBy(currentUser.getUserId());
            menu.setUpdateTime(LocalDateTime.now());
            menu.setDelFlag(0);
            boolean save = save(menu);
            if (save) {
                return R.ok().data(true);
            }
        } catch (Exception e) {
            log.warn("保存菜单异常:{},参数:{}", e.getMessage(), JSONUtil.toJsonStr(req));
        }
        return R.fail(CodeEnum.ADD_MENU_ERROR).data(false);
    }

    /**
     * 获取菜单
     *
     * @param id id
     * @return {@link R}
     */
    @Override
    public R<SysMenu> queryMenu(Long id) {
        LambdaQueryWrapper<SysMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysMenu::getId, id);
        wrapper.eq(SysMenu::getDelFlag, DelEnum.NOT_DEL.val);
        SysMenu one = getOne(wrapper);
        return R.ok().data(one);
    }

    /**
     * 编辑
     *
     * @param currentUser  铜
     * @param req 要求事情
     * @return {@link R}
     */
    @Override
    public R<Boolean> edit(CurrentUser currentUser, MenuReqVO req) {
        Long id = req.getId();
        SysMenu menu = getById(id);
        //菜单名称
        String menuName = req.getMenuName();
        if (StrUtil.isNotBlank(menuName)) {
            menu.setMenuName(menuName);
        }
        //路由地址
        String path = req.getPath();
        if (StrUtil.isNotBlank(path)) {
            menu.setPath(path);
        }
        //组件路径
        String component = req.getComponent();
        if (StrUtil.isNotBlank(component)) {
            menu.setComponent(component);
        }
        //父级id
        Integer pid = req.getPid();
        if (pid != null) {
            menu.setPid(pid);
        }
        //组件路径
        Integer display = req.getDisplay();
        if (display != null) {
            menu.setDisplay(display);
        }
        //组件路径
        Integer state = req.getState();
        if (state != null) {
            menu.setState(state);
        }
        //组件路径
        String perms = req.getPerms();
        if (StrUtil.isNotBlank(perms)) {
            menu.setPerms(perms);
        }
        //组件路径
        Integer type = req.getType();
        if (type != null) {
            menu.setType(type);
        }
        //组件路径
        String icon = req.getIcon();
        if (StrUtil.isNotBlank(icon)) {
            menu.setIcon(icon);
        }
        //组件路径
        String remark = req.getRemark();
        if (StrUtil.isNotBlank(remark)) {
            menu.setMenuName(remark);
        }
        //组件路径
        Integer sort = req.getSort();
        if (sort != null) {
            menu.setSort(sort);
        }
        menu.setUpdateBy(currentUser.getUserId());
        menu.setUpdateTime(LocalDateTime.now());
        boolean update;
        try {
            update = updateById(menu);
        } catch (Exception e) {
            log.warn("修改菜单异常:{},参数:{}", e.getMessage(), JSONUtil.toJsonStr(req));
            return R.fail(CodeEnum.UPDATE_MENU_ERROR).data(false);
        }
        return R.ok().data(update);
    }
}
